package com.zhuqi.websocket;

import cn.hutool.core.util.StrUtil;
import com.zhuqi.user.UserCache;
import com.zhuqi.util.NettyChatUtil;
import com.zhuqi.util.WebsocketUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@Component
@ServerEndpoint(value = "/ws")
@Log4j2
public class FaceVerifyController {

	/**
	 * 连接事件，加入注解
	 *
	 * @param session 会话
	 */
	@OnOpen
	public void onOpen(Session session) {
		String id = session.getId();
		// 添加到session的映射关系中
		WebsocketUtil.addSession(id, session);
		//获取链接的设备信息
		//判断是否存在人脸验证设备与服务器 socket的链接
		//已连接
		WebsocketUtil.sendMessage(id, "欢迎使用！");
	}

	/**
	 * 连接事件，加入注解
	 * 用户断开链接
	 *
	 * @param session session
	 */
	@OnClose
	public void onClose(Session session) {
		String deviceId = WebsocketUtil.getParam(WebsocketUtil.sessionKey, session);
		// 删除映射关系
		WebsocketUtil.removeSession(deviceId);
	}

	/**
	 * 当接收到用户上传的消息
	 *
	 * @param session session
	 */
	@OnMessage
	public void onMessage(Session session, String message) {
		log.info("websocket onMessage()session{}, message{}", session, message);
		String id = session.getId();
		String[] splitString = message.split(" ");
		String businessType = splitString[0];
		String userName = splitString[1];
		String content = splitString[2];
		if (StrUtil.isBlank(businessType) || StrUtil.isBlank(userName) || StrUtil.isBlank(content)) {
			WebsocketUtil.sendMessage(session, "消息格式有误：example: type name content");
			return;
		}

		// 判断是否登陆
		if (!WebsocketUtil.isLogging(id)) {
			// 登陆操作
			if ("logging".equalsIgnoreCase(businessType)) {
				WebsocketUtil.addUseCache(userName, content,session);
				if (NettyChatUtil.doLogging(userName, content, session)) {
					WebsocketUtil.sendMessage(session, "登陆中....，请稍后");
				} else {
					WebsocketUtil.sendMessage(session, "登陆失败");
				}
			} else {
				WebsocketUtil.sendMessage(session, "没有登陆不能发消息!!!");
			}
		} else {
			UserCache currentUser = WebsocketUtil.getCurrentUser(session.getId());
			// 退出
			if ("quit".equalsIgnoreCase(businessType)) {
				NettyChatUtil.logOut(userName, content, session);
			}
			if ("logging".equalsIgnoreCase(businessType)) {
				WebsocketUtil.sendMessage(session, "请勿重复登陆！");
			}
			// 发送消息
			if ("send".equalsIgnoreCase(businessType)) {
				// 发送给自己，不经过Netty
				WebsocketUtil.sendMessage(session, StrUtil.format("{}:{}", currentUser.getName(), content));
				NettyChatUtil.sendMessage(userName, content, session);
			}
		}

	}

	/**
	 * 处理用户活连接异常
	 *
	 * @param session session
	 * @param throwable throwable
	 */
	@OnError
	public void onError(Session session, Throwable throwable) {
		try {
			if (session.isOpen()) {
				session.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			WebsocketUtil.removeSession(session.getId());
		}
		throwable.printStackTrace();
	}
}
